#!/bin/bash

# AWK运维三剑客演示脚本
# 展示AWK在实际运维场景中的强大功能

echo "🚀 AWK运维三剑客演示平台"
echo "================================"
echo ""

# 创建必要的目录
mkdir -p data scripts results

# 设置脚本可执行权限
chmod +x scripts/*.awk

echo "📊 1. 基础AWK功能演示"
echo "--------------------------------"

echo "🔍 提取用户名和UID (模拟 /etc/passwd):"
echo "root:x:0:0:root:/root:/bin/bash
nginx:x:33:33:www-data:/var/www:/usr/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/false
postgres:x:26:26:PostgreSQL:/var/lib/postgresql:/bin/bash" | awk -F: '{print "用户:", $1, "UID:", $3}'

echo ""
echo "📈 统计字段数量:"
echo "192.168.1.1 GET /index.html 200
10.0.0.1 POST /api/login 401
203.0.113.1 GET /images/logo.png 200" | awk '{print "记录", NR ":", "字段数 =", NF, "内容 =", $0}'

echo ""
echo "🧮 数学运算演示:"
echo "100 200 300
150 250 350
200 300 400" | awk '{sum = $1 + $2 + $3; avg = sum/3; print "行", NR ":", "总和 =", sum, "平均值 =", avg}'

echo ""
echo "================================"
echo "📋 2. 日志分析演示"
echo "--------------------------------"

echo "🔍 分析Nginx访问日志..."
awk -f scripts/log_analyzer.awk data/nginx_access.log > results/log_analysis.txt
echo "✅ 日志分析完成，结果保存到 results/log_analysis.txt"
echo ""
echo "📊 分析结果预览:"
head -20 results/log_analysis.txt

echo ""
echo "================================"
echo "💻 3. 系统性能监控演示"
echo "--------------------------------"

echo "🔍 分析系统性能数据..."
awk -f scripts/system_monitor.awk data/top_output.txt > results/system_report.txt
echo "✅ 系统监控完成，结果保存到 results/system_report.txt"
echo ""
echo "📊 监控结果预览:"
head -25 results/system_report.txt

echo ""
echo "================================"
echo "🎯 4. 高级AWK特性演示"
echo "--------------------------------"

echo "🔄 多维数组统计 - IP访问频次:"
awk '
BEGIN {print "=== IP访问统计 ==="}
{
    # 提取IP地址 (第一个字段)
    ip_count[$1]++
    total++
}
END {
    print "总请求数:", total
    print "唯一IP数:", length(ip_count)
    print "\nIP访问排行:"
    for(ip in ip_count) {
        printf "%-15s : %d 次访问\n", ip, ip_count[ip]
    }
}' data/nginx_access.log

echo ""
echo "🎨 条件分支 - HTTP状态码分类:"
awk '
BEGIN {
    print "=== HTTP状态码分析 ==="
    success=0; redirect=0; client_error=0; server_error=0
}
{
    status = $9
    if (status ~ /^2/) {
        success++
        category = "✅ 成功"
    } else if (status ~ /^3/) {
        redirect++
        category = "🔄 重定向"
    } else if (status ~ /^4/) {
        client_error++
        category = "❌ 客户端错误"
    } else if (status ~ /^5/) {
        server_error++
        category = "💥 服务器错误"
    }
    printf "%-15s %s %s -> %s\n", $1, $6, status, category
}
END {
    print "\n=== 状态码统计 ==="
    printf "成功 (2xx): %d\n", success
    printf "重定向 (3xx): %d\n", redirect
    printf "客户端错误 (4xx): %d\n", client_error
    printf "服务器错误 (5xx): %d\n", server_error
    
    total = success + redirect + client_error + server_error
    if (total > 0) {
        printf "\n成功率: %.1f%%\n", (success/total)*100
        printf "错误率: %.1f%%\n", ((client_error+server_error)/total)*100
    }
}' data/nginx_access.log

echo ""
echo "🕒 时间序列分析 - 请求时间分布:"
awk '
BEGIN {print "=== 请求时间分析 ==="}
{
    # 提取时间戳中的分钟信息
    if (match($4, /[0-9]{2}:[0-9]{2}:[0-9]{2}/)) {
        time = substr($4, RSTART, RLENGTH)
        minute = substr(time, 4, 2)
        minute_count[minute]++
        total++
    }
}
END {
    print "总请求数:", total
    print "\n每分钟请求分布:"
    for (i=0; i<=59; i++) {
        min = sprintf("%02d", i)
        if (minute_count[min] > 0) {
            printf "第 %s 分钟: %d 个请求\n", min, minute_count[min]
        }
    }
}' data/nginx_access.log

echo ""
echo "================================"
echo "🛠️  5. 实用AWK一行命令"
echo "--------------------------------"

echo "📝 常用AWK命令示例:"
echo ""
echo "1️⃣  提取特定列:"
echo "   awk '{print \$1, \$9}' nginx.log"
echo ""
echo "2️⃣  过滤特定条件:"
echo "   awk '\$9 == 404 {print \$1, \$7}' nginx.log"
echo ""
echo "3️⃣  计算总和:"
echo "   awk '{sum += \$10} END {print \"总流量:\", sum}' nginx.log"
echo ""
echo "4️⃣  统计唯一值:"
echo "   awk '{count[\$1]++} END {for(ip in count) print ip, count[ip]}' nginx.log"
echo ""
echo "5️⃣  格式化输出:"
echo "   awk '{printf \"%-15s %s\\n\", \$1, \$7}' nginx.log"

echo ""
echo "================================"
echo "🎉 演示完成！"
echo "================================"
echo ""
echo "📁 生成的文件:"
echo "   📊 results/log_analysis.txt - 详细日志分析报告"
echo "   📈 results/system_report.txt - 系统性能监控报告"
echo ""
echo "🌐 打开 index.html 查看交互式学习界面"
echo "💡 AWK真正的威力在于其灵活性和可编程性！"
echo ""